package org.dim.oa.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 *  spring security默认使用表单登录，这里换成json方式登录
 */
public class CustomUnamePwdAuthenFilter extends UsernamePasswordAuthenticationFilter {
    @Autowired
    PasswordEncoder passwordEncoder;
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String contentType = request.getContentType();
        System.out.println(contentType);
        if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)||request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)) {
            ObjectMapper mapper = new ObjectMapper();
            UsernamePasswordAuthenticationToken authRequest = null;
            try (InputStream is = request.getInputStream()) {
                Map<String,String> authenticationBean = mapper.readValue(is, Map.class);
                System.out.println(authenticationBean);
                authRequest = new UsernamePasswordAuthenticationToken(
                        //md5加密一波，后台内存中存的是123456
                        //或者用passwordEncoder加密
                        //本来应该用passwordEncoder.encode(对密码加密的）
                        authenticationBean.get("userName"), authenticationBean.get("password"));
            } catch (IOException e) {
                System.out.println(e.getMessage());
                authRequest = new UsernamePasswordAuthenticationToken(
                        "", "");
            } finally {
                setDetails(request, authRequest);
                return this.getAuthenticationManager().authenticate(authRequest);
            }
        }
        else {
            //如果不是json的话，那就走表单形式的逻辑---妙啊
            return super.attemptAuthentication(request, response);
        }
    }
}